package org.ws.edu.task2.commands;

import org.ws.edu.task2.Element;
import org.ws.edu.task2.ICommand;
import org.ws.edu.task2.VirtualFileSystem;
import org.ws.edu.task2.exceptions.ExtensionLengthException;
import org.ws.edu.task2.exceptions.IncorrectPathException;
import org.ws.edu.task2.exceptions.IncorrectSymbolsException;
import org.ws.edu.task2.exceptions.NameLengthException;

public class Move implements ICommand {

    private String[] path1 = null;
    private String[] path2 = null;
    private Element firstElement = null;
    private Element secondElement = null;

    public Move(String path1, String path2) {
        this.path1 = path1.split("\\\\");
        this.path2 = path2.split("\\\\");
    }

    @Override
    public void execute(VirtualFileSystem vfs) throws ExtensionLengthException, NameLengthException, IncorrectSymbolsException,
            IncorrectPathException {

        firstElement = vfs.getElementByPath(path1);
        secondElement = vfs.getElementByPath(path2);
        validPath(vfs);
        if (vfs.isCurrentFolder(firstElement)) {
            if (firstElement.elements.contains(new Element(path1[path1.length - 1], true))) {
                secondElement.elements.add(firstElement.elements.ceiling(new Element(path1[path1.length - 1], true)));
                vfs.changeCurrentElement(secondElement.elements.ceiling(new Element(path1[path1.length - 1], true)));
                firstElement.elements.remove(new Element(path1[path1.length - 1], true));
            }
            if (firstElement.elements.contains(new Element(path1[path1.length - 1], false))) {
                secondElement.elements.add(firstElement.elements.ceiling(new Element(path1[path1.length - 1], false)));
                vfs.changeCurrentElement(secondElement);
                firstElement.elements.remove(new Element(path1[path1.length - 1], false));
            }
        } else if (firstElement.elements.contains(vfs.getCurrentFolder())) {
            secondElement.elements.add(vfs.getCurrentFolder());
            vfs.changeCurrentElement(secondElement.elements.ceiling(new Element(path1[path1.length - 1], true)));
            firstElement.elements.remove(new Element(path1[path1.length - 1], true));

        } else {
            throw new IncorrectPathException();
        }

    }

    @Override
    public void validPath(VirtualFileSystem vfs) throws ExtensionLengthException, NameLengthException, IncorrectSymbolsException,
            IncorrectPathException {

        if (!secondElement.isFolder()) {
            throw new IncorrectPathException();
        }

    }

}
